<template>
  <div>
    <el-dialog v-model="dialogVisible" width="950" :close-on-click-modal="false" :show-close="false">
      <template #header>
        <div class="top">
          <p>{{ addDataTitle === 'add' ? '新增日程' : '编辑日程' }}</p>
          <el-icon @click="handleClose">
            <Close />
          </el-icon>
        </div>
      </template>
      <div class="content">
        <el-form :label-position="'top'" ref="ruleFormRef" :rules="rules" label-width="auto" :model="ruleForm">
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="标题" prop="label">
                <el-input v-model="ruleForm.label" placeholder="请输入日程标题" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="开始日期" prop="startDate">
                <el-date-picker style="width: 100%;" v-model="ruleForm.startDate" type="datetime"
                  placeholder="Select date and time" format="YYYY-MM-DD HH:mm" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束日期" prop="endDate">
                <el-date-picker style="width: 100%;" v-model="ruleForm.endDate" type="datetime"
                  :disabled-date="disabledDate" placeholder="Select date and time" format="YYYY-MM-DD HH:mm" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="日程类别" prop="type">
                <el-select v-model="ruleForm.type" placeholder="请选择日程类别">
                  <el-option v-for="item in ScheduleTypeAllList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预计工时" prop="workHours">
                <el-input-number class="mx-4" v-model="ruleForm.workHours" :min="0.5" :max="24" :step="0.5"
                  controls-position="right">
                  <template #append>小时</template>
                </el-input-number>

              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="资源" prop="resourceIds">
                <el-select v-model="ruleForm.resourceIds" placeholder="请选择资源" multiple collapse-tags>
                  <el-option v-for="item in ResourceAllList" :key="item.resourceId" :label="item.resourceName"
                    :value="item.resourceId" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="日历" prop="scheduleId">
                <el-select v-model="ruleForm.scheduleId"
                  :disabled="addDataTitle == 'edit' && calendarObj.scheduleId != ''" placeholder="请选择日历">
                  <el-option v-for="item in scheduleAllList" :key="item.id" :label="item.scheduleName"
                    :value="item.id" />
                </el-select>

              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="允许反馈" prop="feedBack">
                <el-select v-model="ruleForm.feedBack" placeholder="请选择反馈方式">
                  <el-option label="是：参与人可选择参加、暂定、谢绝" value="1" />
                  <el-option label="否：无需参与人反馈" value="2" />
                </el-select>

              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="日程颜色" prop="calendarColor">
                <el-color-picker v-model="ruleForm.calendarColor" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="参与人员" prop="feedBack">
                <div class="add-member">
                  <el-button :icon="Plus" circle @click="opneUser" />
                  <div class="member-list">
                    <el-tag v-for="item in ruleForm.member" closable type="primary"
                      @close="handleCloseTag(item)">{{
                        item.nickName }}</el-tag>
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="提醒" prop="feedBack">
                <el-select v-model="ruleForm.remindTime" placeholder="请选择时间" style="width: 175px;margin-right: 10px;">
                  <el-option v-for="option in timeOptions" :key="option" :label="option" :value="option" />
                </el-select>
                <el-select v-model="remindTimeType" style="width: 175px" @change="updateTimeOptions">
                  <el-option label="分钟" value="minute" />
                  <el-option label="小时" value="hour" />
                  <el-option label="天" value="day" />
                </el-select>

              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="内容" prop="content">
                <el-input v-model="ruleForm.content" type="textarea" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>

        </div>
      </template>
    </el-dialog>
    <!-- <SelectUser ref="selectUserRef" @sureDialogTransferClick="sureDialogTransferClick" /> -->
    <schedule-select-people ref="ScheduleSelectPeopleRefs"
      @confirmClick="ScheduleSelectPeople_confirmClick"></schedule-select-people>
  </div>
</template>


<script lang="ts" setup>
import { Plus } from '@element-plus/icons-vue'
import {
  apiSysCalendarTypeGetAllSysCalendarTypes,
  apiSysResourceGetAllResource,
  sysScheduleAll,
  apiSysCalendarCreate,
  apiSysCalendarGetDetailShowId,
  sysCalendarUpadate
} from '@/api/calendar'
// import SelectUser from '@/views/components/select-user-check/select-user.vue'
import ScheduleSelectPeople from "./schedule-select-people.vue"


const emit = defineEmits(['update:addDataTitle', 'confirm']) // 支持 `type.sync`
const props = defineProps({
  addDataTitle: {
    type: String,
  }
})

const route = useRoute()
const dialogVisible = ref(false)
const remindTimeType = ref('minute')
const ScheduleTypeAllList = ref([])
const ResourceAllList = ref([])
const scheduleAllList = ref([])
const ScheduleSelectPeopleRefs = ref(null)
const ruleFormRef = ref(null)
const timeOptions = ref([])
const pageType = ref('')
const calendarObj = ref({
  scheduleId: null,
  id: null,
})
const rules = reactive({
  label: [
    { required: true, message: '请输入日程标题', trigger: 'blur' },
  ],
  startDate: [
    { required: true, message: '请选择开始时间', trigger: 'blur' },
  ],
  endDate: [
    { required: true, message: '请选择结束时间', trigger: 'blur' },
  ],
  workHours: [
    { required: true, message: '请输入工时', trigger: 'blur' },
  ],
  scheduleId: [
    { required: true, message: '请选择日历', trigger: 'blur' },
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
  ]

})
const ruleForm = reactive({
  label: '',
  startDate: '',
  endDate: '',
  type: null,
  workHours: null,
  resourceIds: [],
  scheduleId: "",
  feedBack: "",
  calendarColor: "#3fdcbf",
  remindTime: "15",
  content: "",
  member: []
})
const updateTimeOptions = () => {
  if (remindTimeType.value === "minute") {
    timeOptions.value = ['5', '10', '15', '20', '25', '30', '35', '40', '45', '50', '55']
  } else if (remindTimeType.value === "hour") {
    timeOptions.value = Array.from({ length: 23 }, (_, i) => (i + 1).toString()) // 1-23 
  } else if (remindTimeType.value === "day") {
    timeOptions.value = Array.from({ length: 30 }, (_, i) => (i + 1).toString()) // 1-30
  }
}
updateTimeOptions()
watch(remindTimeType, (newType) => {
  if (newType === "minute") {
    ruleForm.remindTime = '5'
  } else if (newType === "hour") {
    ruleForm.remindTime = '1'
  } else if (newType === "day") {
    ruleForm.remindTime = '1'
  }
})
watch(() => ruleForm.startDate, (newStartDate) => {
  if (props.addDataTitle == 'add') {
    if (newStartDate) {
      const startDate = new Date(newStartDate)
      const endDate = new Date(ruleForm.endDate || newStartDate) // 如果没有结束日期，则使用开始日期作为结束日期
      endDate.setFullYear(startDate.getFullYear())
      endDate.setMonth(startDate.getMonth())
      endDate.setDate(startDate.getDate())
      ruleForm.endDate = endDate.toISOString()
    }
  }
})

const disabledDate = (time) => {
  return time.getTime() < new Date(ruleForm.startDate).getTime() - 86400000
}


// 获取全部日程类别
const getScheduleTypeAll = async () => {
  let res = await apiSysCalendarTypeGetAllSysCalendarTypes({
    name: ""
  })
  if (res.code == 200) {
    ScheduleTypeAllList.value = res.data
  }
}
// 获取全部日历资源
const getResourceAll = async () => {
  let res = await apiSysResourceGetAllResource()
  if (res.code == 200) {
    ResourceAllList.value = res.data.resource
  }
}
// 获取全部日历 
const getCalendarTypeAll = async () => {
  const res = await sysScheduleAll({
    scheduleName: ""
  })
  if (res.code == 200) {
    scheduleAllList.value = res.data
  }
}

// 打开人员弹窗
const opneUser = () => {
  if (ruleForm.scheduleId == "") {
    ElMessage.error('请选择日历')
    return
  }
  if (ScheduleSelectPeopleRefs.value) {
    ScheduleSelectPeopleRefs.value.dialogTransfer = true
    ScheduleSelectPeopleRefs.value.getTableData(ruleForm.scheduleId)
    if (ruleForm.member.length > 0) {
      ScheduleSelectPeopleRefs.value.rightUserList = ruleForm.member
    } else {
      ScheduleSelectPeopleRefs.value.rightUserList = []
    }
    // 
  }

}

const ScheduleSelectPeople_confirmClick = (val) => {
  console.log(val, 'val')
  ruleForm.member = val
}
// 删除标签
const handleCloseTag = (item: any) => {
  ruleForm.member.splice(ruleForm.member.indexOf(item), 1)
}

const addSchedule = async (params: any) => {
  const res = await apiSysCalendarCreate(params)
  if (res.code == 200) {
    ElMessage.success('创建成功')
    handleClose()
    emit('confirm', pageType.value)
  }
}

// 确定数据
const submitForm = async (formEl: any) => {
  if (!formEl) return
  await formEl.validate((valid: any, fields: any) => {
    if (valid) {
      let params = {
        label: ruleForm.label || "",
        startDate: ruleForm.startDate
          ? new Date(ruleForm.startDate).toLocaleString("zh-CN", { hour12: false }).replace(/\//g, "-")
          : "",
        endDate: ruleForm.endDate
          ? new Date(ruleForm.endDate).toLocaleString("zh-CN", { hour12: false }).replace(/\//g, "-")
          : "",
        type: ruleForm.type || null,
        workHours: ruleForm.workHours,
        resourceIds: ruleForm.resourceIds || [],
        scheduleId: ruleForm.scheduleId || "",
        feedBack: ruleForm.feedBack || "",
        calendarColor: ruleForm.calendarColor || "",
        remindTime: ruleForm.remindTime || "",
        content: ruleForm.content || "",
        userIds: ruleForm.member.map((item: any) => item.id) || []
      }
      const timeUnitToMultiplier = {
        minute: 1,
        hour: 60,
        day: 60 * 24
      }
      if (timeUnitToMultiplier[remindTimeType.value]) {
        params.remindTime = (Number(ruleForm.remindTime) * timeUnitToMultiplier[remindTimeType.value]).toString()
      }
      if (props.addDataTitle == "add") {
        addSchedule(params)
      } else {
        editSchedule(params)
      }
    } else {
      console.log('error submit!', fields)
      return false
    }
  })
}
const editSchedule = (params) => {
  params.id = calendarObj.value.id
  sysCalendarUpadate(params).then(res => {
    if (res.code == 200) {
      ElMessage.success('修改成功')
      handleClose()
      setFromData(calendarObj.value.id)
      emit('confirm', pageType.value, calendarObj.value.id)
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const openDialog = (info: any, type?) => {
  // console.log(info)
  pageType.value = type
  dialogVisible.value = true

  if (props.addDataTitle == 'edit') {
    setFromData(info.id)
  } else {
    ruleForm.member = []
    if (route.query.scheduleId) {
      ruleForm.scheduleId = parseInt(route.query.scheduleId)
    }
    if (info) {
      // 获取当前时间的小时、分钟和秒
      const currentTime = new Date()
      const hours = currentTime.getHours()
      const minutes = currentTime.getMinutes()
      const seconds = currentTime.getSeconds()

      // 将 info.dateStr 的日期拼接当前时间
      const startDateTime = new Date(`${info.dateStr}T${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`)
      ruleForm.startDate = startDateTime.toISOString()

      // 设置结束日期为当前时间的30分钟后
      const endDateTime = new Date(startDateTime.getTime() + 30 * 60 * 1000) // 当前时间加30分钟
      ruleForm.endDate = endDateTime.toISOString()
    } else {
      const currentTime = new Date()
      const startDateTime = currentTime
      ruleForm.startDate = startDateTime.toISOString()

      // 设置结束日期为当前时间的30分钟后
      const endDateTime = new Date(startDateTime.getTime() + 30 * 60 * 1000)
      ruleForm.endDate = endDateTime.toISOString()
    }
  }



  getScheduleTypeAll()
  getResourceAll()
  getCalendarTypeAll()
}
const setFromData = (id) => {
  apiSysCalendarGetDetailShowId(id).then(res => {
    if (res.code == 200) {
      calendarObj.value = res.data.calendar
      ruleForm.label = res.data.calendar.label
      ruleForm.calendarColor = res.data.calendar.calendarColor
      ruleForm.startDate = res.data.calendar.startDate
      ruleForm.endDate = res.data.calendar.endDate
      ruleForm.type = Number(res.data.calendar.type)
      ruleForm.workHours = res.data.calendar.workHours
      ruleForm.resourceIds = JSON.parse(res.data.calendar.resourceId || '[]')
      ruleForm.scheduleId = res.data.calendar.scheduleId
      ruleForm.feedBack = res.data.calendar.feedBack
      ruleForm.remindTime = res.data.calendar.remindTime
      ruleForm.content = res.data.calendar.content
      ruleForm.member = res.data.userFeedBack
      ruleForm.member.forEach(member => {
        member.nickName = member.userName
      })
    }
  })
}

const handleClose = () => {
  dialogVisible.value = false
  ruleFormRef.value?.resetFields()
}

defineExpose({
  openDialog
})

</script>


<style lang="scss" scoped>
p {
  margin: 0;
}

:deep(.el-dialog__header) {
  border-bottom: none !important;
  padding: 0 !important;

  .top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 18px;

    i {
      cursor: pointer;
    }
  }
}

:deep(.el-input-number) {
  width: 100%;
  margin: 0px;

  .el-input__inner {
    text-align: left;
  }
}

.add-member {
  display: flex;
}

.member-list {
  .el-tag {
    margin-left: 10px;
  }
}
</style>